package com.hengshan.controller;

import com.alibaba.fastjson2.JSONObject;
import com.hengshan.common.ResultBody;
import com.hengshan.common.utils.BeanCopyUtil;
import com.hengshan.common.utils.SecurityUtils;
import com.hengshan.domain.LoginBody;
import com.hengshan.domain.entity.Role;
import com.hengshan.domain.entity.User;
import com.hengshan.domain.vo.RouterVo;
import com.hengshan.domain.vo.UserInfoVo;
import com.hengshan.service.impl.LoginService;
import com.hengshan.service.impl.MenuServiceImpl;
import com.hengshan.service.impl.RoleServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;

@Validated
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final LoginService loginService;
    private final MenuServiceImpl menuService;
    private final RoleServiceImpl roleService;
    private final ServerProperties serverProperties;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public JSONObject login(@Validated @RequestBody LoginBody loginBody) {
        return loginService.login(loginBody);
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public ResultBody logout() {
        return loginService.logout();
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @RequestMapping("/getInfo")
    public JSONObject getInfo() {
        User user = SecurityUtils.getUser();
        List<String> perms = menuService.selectPermsByUser(user);
        List<Role> roles = roleService.selectRolesByUser(user);
        UserInfoVo userInfoVo = BeanCopyUtil.copyBean(user, UserInfoVo.class);
        userInfoVo.setRoles(roles);
        userInfoVo.setAvatar("http://localhost:" + serverProperties.getPort() + "/images/" + user.getAvatar());
        JSONObject res = new JSONObject();
        res.put("user", userInfoVo);
        res.put("permissions", perms);
        res.put("roles", roles.stream().map(Role::getRoleKey).collect(Collectors.toList()));
        return res;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @RequestMapping("/getRouters")
    public List<RouterVo> getRouters() {
        return menuService.getRouters(SecurityUtils.getUser());
    }

    /**
     * 请求本地图片
     */
    @RequestMapping(value = {"/images/{fileName}", "/images/{date}/{fileName}"})
    public void getImage(@PathVariable(value = "fileName") String fileName, @PathVariable(value = "date", required = false) String date,
                         HttpServletResponse response) throws IOException {
        FileInputStream fis = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (fileType.equals(".jpg") || fileType.equals(".jpeg")) {
            response.setContentType("image/jpeg");
        } else if (fileType.equals(".gif")) {
            response.setContentType("image/gif");
        } else if (fileType.equals(".png")) {
            response.setContentType("image/png");
        }
        //System.out.println(date + "  " + fileName);
        try {
            OutputStream out = response.getOutputStream();
            String imageRootPath = System.getProperty("user.dir") + "/images/";
            if (null == date) {
                fis = new FileInputStream(imageRootPath + fileName);
            } else {
                fis = new FileInputStream(imageRootPath + date + "/" + fileName);
            }
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fis.close();
        }
    }
}